//
//  HYFileDownloadItemViewModel.m
//  XPlayer
//
//  Created by liguoqing on 2023/10/12.
//

#import "HYFileDownloadItemViewModel.h"
#import <HYDownloader/HYBriefDownloadConfig.h>
#import <HYDownloader/HYBriefDownloadTaskManager.h>
#import "HYFileDownloadService.h"
#import "HYAlertActionView.h"
#import "HYHomeVideoModel.h"

@interface HYFileDownloadItemViewModel ()

@property (nonatomic, strong) HYFileDownloadTask *downloadTask;

@property (nonatomic, strong) HYFileDownloadModel *downloadModel;

@end

@implementation HYFileDownloadItemViewModel

- (instancetype)initWithDownloadModel:(HYFileDownloadModel *)downloadModel
{
    self = [super init];
    if(self){
        self.downloadModel = downloadModel;
        self.fileName = downloadModel.fileName;
        self.fileUrl = downloadModel.fileUrl;
        self.fileType = downloadModel.fileType;
        self.fileSize = downloadModel.fileSize;
        self.imageName = downloadModel.imageName;
        self.progress = downloadModel.progress;
        self.createDate = downloadModel.createDate;
        self.downloadDate = downloadModel.downloadDate;
        self.downloadStatus = downloadModel.downloadStatus;
        self.folderIdentification = downloadModel.folderIdentification;
        self.isPrivate = downloadModel.isPrivate;
        
        NSString *lastName = [downloadModel.fileUrl lastPathComponent];
        NSString *downloadID = [NSString stringWithFormat:@"%@%@",lastName,downloadModel.createDate];
        self.downloadTask = [[HYFileDownloadService sharedInstance] findOrCreateOneTaskWithDownloadID:downloadID
                                                                                        downloadURL:downloadModel.fileUrl
                                                                                             fileName:lastName];
        if(self.downloadTask.status == HYDownloadStatus_Downloading){
            // 是否是强制退出
            BOOL isForceExit = [[NSUserDefaults standardUserDefaults] boolForKey:@"DownloadTask"];
            if(isForceExit){
                [self checkMobileNetWarning:^{
                    [self.downloadTask start];
                    [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"DownloadTask"];
                }];
            }
        }else if(self.downloadTask.status == HYDownloadStatus_Default || self.downloadTask.status == HYDownloadStatus_Waiting){
            [self startOrPauseDownload];
        }else if (self.downloadTask.status == HYDownloadStatus_Completed){
            if(downloadModel.progress<1.0){
                NSInteger fileBytes = [HYFileManager getSingleFileSizeWithFilePath:self.downloadTask.filePath];
                self.fileSize = [CommUtls getSize:@(fileBytes)];
                downloadModel.fileSize = self.fileSize;
                downloadModel.progress = 1.0;
                [downloadModel updateToDB];
            }
        }
    }
    return self;
}

#pragma mark - 开始或暂停下载
- (void)startOrPauseDownload
{
    if(self.downloadTask.status == HYDownloadStatus_Default || self.downloadTask.status == HYDownloadStatus_Pause || self.downloadTask.status == HYDownloadStatus_Error){
        [self checkMobileNetWarning:^{
            [[HYBriefDownloadTaskManager sharedInstance] startOrResumeAll:@[self.downloadTask]];
        }];
    }else if (self.downloadTask.status == HYDownloadStatus_Downloading || self.downloadTask.status == HYDownloadStatus_Waiting){
        [[HYBriefDownloadTaskManager sharedInstance] pauseAll:@[self.downloadTask]];
    }
}


#pragma mark -流量提醒
// 流量提醒
- (void)checkMobileNetWarning:(dispatch_block_t)startBlock
{
    if ([HYNetWorkManager shareManager].currentReachabilityStatus == NotReachable) {
        // 无网络
        [HYHub showMessage:NSLocalizedString(@"无网络",nil)];
    }else if ([HYNetWorkManager shareManager].currentReachabilityStatus == ReachableViaWWAN){
        // 使用移动网络
        if ([self ignoreMobileNetWarning]) {
            if (startBlock) {
                startBlock();
            }
        }else{
            @weakify(self);
            [HYAlertActionView showViewControler:[CommUtls getCurrentVC] title:NSLocalizedString(@"温馨提示",nil) message:NSLocalizedString(@"您正在使用非WiFi网络\n下载将产生流量",nil) actionTitle:@[NSLocalizedString(@"下载且不再提示",nil),NSLocalizedString(@"继续下载",nil)] sureBlock:^{
                @strongify(self);
                [self recordIgnoreMobileNetWarning];
                if (startBlock) {
                    startBlock();
                }
            } cancelBlock:^{
                if (startBlock) {
                    startBlock();
                }
            }];
        }
    }else{
        // 可以正常下载
        if (startBlock) {
            startBlock();
        }
    }
}
// 是否忽略流量提醒
- (BOOL)ignoreMobileNetWarning
{
    return [HYMineSetManager shareManager].isAllowNetwork;
}
// 记录忽略流量提醒
- (void)recordIgnoreMobileNetWarning
{
    [HYMineSetManager shareManager].isAllowNetwork = YES;
    [HYBriefDownloadConfig sharedInstance].onlyWiFiDownload = NO;
    [kNotificationCenter postNotificationName:kSetRefreshListNotification object:nil];
}

// 下载完成
- (void)downloadComplete:(NSString *)totalBytes;
{
    self.downloadModel.progress = 1.0;
    self.downloadModel.fileSize = totalBytes;
    self.downloadModel.downloadStatus = 1.0;
    [self.downloadModel updateToDB];
}

// 移除下载
- (BOOL)deleteDownload
{
    [self.downloadTask cancel];
    return [self.downloadModel deleteToDB];
}

- (void)saveCurrentDownloadProgress:(CGFloat)progress downloadSize:(NSString *)downloadSize
{
    self.downloadModel.progress = progress;
    self.downloadModel.fileSize = downloadSize;
    [self.downloadModel updateToDB];
}

- (NSString *)fetchDownloadUrl
{
    NSString *lastName = [self.downloadModel.fileUrl lastPathComponent];
    return [HYFileManager videoDownloadPathWithFileName:lastName];
}

@end
